#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpSever.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;


using http_handler_t = std::function<void(HttpRequest&,HttpResponse&)>;


class HttpServer
{
public:
    HttpServer(int port):
        _tsvr(std::make_unique<TcpServer>(port))
    {

    }
    void Resigster(std::string funcname,http_handler_t func)
    {
        _route[funcname] = func;
    }
    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd,InetAddr client){
            return this->HandlerHttpRequest(sockfd,client);
        });
        _tsvr->Loop();
    }
    bool SafeCheck(const std::string& service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }
    bool HandlerHttpRequest(SockPtr sockfd,InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "HttpServer: get a new client: " << sockfd->Fd() 
        << " addr info: " << client.Addr();
        std::string http_request;
        //目前我们读取到的是最原始的信息
        sockfd->Recv(&http_request);
        
        HttpRequest req;
        req.Deserialize(http_request);

        HttpResponse resp;
        //1.请求静态资源
        //2.提交参数,交互设置
        if(req.IsHasArgs())
        {
            std::string service = req.Path();
            if(SafeCheck(service))
            {
                _route[service](req,resp);//login
            }
            else
            {
                resp.Build(req);
            }
        }
        else
        {
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);
        return true;
    }
    ~HttpServer()
    {

    }
private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string,http_handler_t> _route; //功能路由
};


